package com.pro.ydl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.pro.ydl.MainHomeActivity.DaySpinnerSelectedListener;
import com.pro.ydl.MainHomeActivity.MonthSpinnerSelectedListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import YDLControl.Control;

public class UserRegisterActivity extends Activity {
	private final Handler handle = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			if(progdialogRegister.isShowing())
			{
				progdialogRegister.dismiss();
			}
			switch(msg.what)
			{
				case REGISTER_CHECK_ID:
				{
					if(0 == msg.arg1)
					{
						ShowToast(UserRegisterActivity.this,"注册失败，请重新尝试");
					}
					else
					{
			    		Intent intent = new Intent();
			    		intent.setClass(UserRegisterActivity.this,MainHomeActivity.class);
			    		UserRegisterActivity.this.startActivity(intent);
			    		UserRegisterActivity.this.finish();
	
					}
				}
				break;
			}
		}
	};
	private static final int REGISTER_CHECK_ID = 1;
	private ProgressDialog progdialogRegister=null;
	private static final String[] month={"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"}; 
	private static String[] days = new String[] {
		"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
		,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
		,"27日","28日","29日","30日","31日"
	}; 
	private static Calendar cal = Calendar.getInstance();
	private static int intCurrentYear =  cal.get(Calendar.YEAR);
	private static int intYearLength = intCurrentYear - 1900 + 1;
	private static String[] year = new String[intYearLength];
	private ArrayAdapter<String> adpBirthdayYear; 
	private ArrayAdapter<String> adpBirthdayMonth; 
	private ArrayAdapter<String> adpBirthdayDay; 
	private Spinner spinnerYear; 
	private Spinner spinnerMonth; 
	private Spinner spinnerDay;
	private boolean bLeapYear = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.user_reg_activity_layout);
		
		//set the button onTouch event
		ImageButton resetBtn = (ImageButton) findViewById(R.id.btnImg_reset);
		resetBtn.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.reset_click));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.reset));
				}
				return false;
			}
		});
		ImageButton gobackBtn = (ImageButton)findViewById(R.id.btnImg_goback);
		gobackBtn.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.back_click));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.back));
				}
				return false;
			}
		});
		
		spinnerYear = (Spinner) findViewById(R.id.registbirthyear);
		spinnerMonth = (Spinner) findViewById(R.id.regbirthdaymonth);
		spinnerDay = (Spinner) findViewById(R.id.regbirthdayday);
		int year_temp = 0;
		for(int i = 0; i < intYearLength ; i++)
		{
			year_temp = 1900 + intYearLength - 1 - i;
			year[i] = String.valueOf(year_temp);
		}
		
		//after the user select the option we can get value by String Text = mySpinner.getSelectedItem().toString();
		adpBirthdayYear = new ArrayAdapter<String>(this,R.layout.spinner_style,year);
		adpBirthdayYear.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
		spinnerYear.setAdapter(adpBirthdayYear); 
		spinnerYear.setVisibility(View.VISIBLE); 
		spinnerYear.setOnItemSelectedListener(new YearSpinnerSelectedListener()); 
		
		adpBirthdayMonth = new ArrayAdapter<String>(this,R.layout.spinner_style,month);
		adpBirthdayMonth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
		spinnerMonth.setAdapter(adpBirthdayMonth); 
		spinnerMonth.setVisibility(View.VISIBLE); 
		spinnerMonth.setOnItemSelectedListener(new MonthSpinnerSelectedListener()); 
		
		adpBirthdayDay = new ArrayAdapter<String>(this,R.layout.spinner_style,days);
		adpBirthdayDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
		spinnerDay.setAdapter(adpBirthdayDay); 
		spinnerDay.setVisibility(View.VISIBLE); 
		spinnerDay.setOnItemSelectedListener(new DaySpinnerSelectedListener()); 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_reg_activity_layout, menu);
		return true;
	}

	public void goback_login(View view) {
		UserRegisterActivity.this.finish();
//		Intent intent = new Intent();
//		intent.setClass(this, UserLoginActivity.class);
//		this.startActivity(intent);
	}

	public void informationSubmit(View view)
	{
		if(checkInformation())
		{
			EditText userEmail = (EditText) findViewById(R.id.registEmail);
			EditText userPassword = (EditText) findViewById(R.id.registPassword);
			EditText userHeight = (EditText) findViewById(R.id.registHeight);
			EditText userWeight = (EditText) findViewById(R.id.registWeight);
			RadioGroup userSex = (RadioGroup) findViewById(R.id.regist_gender);
			String strUserEmail,strUserPassword,strUserSex;
			double strUserHeight,strUserWeight;
			strUserEmail = userEmail.getText().toString();
			strUserPassword = userPassword.getText().toString();
			strUserHeight = Double.parseDouble(userHeight.getText().toString());
			strUserWeight = Double.parseDouble(userWeight.getText().toString());
			if(R.id.registBoy == userSex.getCheckedRadioButtonId())
			{
				strUserSex = "F";
			}
			else
			{
				strUserSex = "M";
			}
			String strBirthday = spinnerYear.getSelectedItem().toString() + "-" + spinnerMonth.getSelectedItem().toString().replace("月", "") + "-" + spinnerDay.getSelectedItem().toString().replace("日", "");

			//web 访问
			RegisterThreadHandle(strUserEmail, strUserPassword, strBirthday, strUserHeight, strUserWeight, strUserSex);
			progdialogRegister = ProgressDialog.show(UserRegisterActivity.this,"正在加载","系统正在处理的 您请求");

		}
	}
	
	public void resetInput(View view) {

		EditText userEmail = (EditText) findViewById(R.id.registEmail);
		EditText userPassword = (EditText) findViewById(R.id.registPassword);
		EditText userConfirmPassword = (EditText) findViewById(R.id.registPasswordConfirm);
		EditText userHeight = (EditText) findViewById(R.id.registHeight);
		EditText userWeight = (EditText) findViewById(R.id.registWeight);
		RadioButton userSex = (RadioButton) findViewById(R.id.registBoy);

		userEmail.setText("");
		userPassword.setText("");
		userConfirmPassword.setText("");
		userHeight.setText("");
		userWeight.setText("");
		userSex.setChecked(true);
	}

	public boolean checkInformation()
	{
		boolean isRight = true;
		EditText userEmail = (EditText) findViewById(R.id.registEmail);
		EditText userPassword = (EditText) findViewById(R.id.registPassword);
		EditText userConfirmPassword = (EditText) findViewById(R.id.registPasswordConfirm);
		EditText userHeight = (EditText) findViewById(R.id.registHeight);
		EditText userWeight = (EditText) findViewById(R.id.registWeight);
		if(!isEmail(userEmail.getText().toString()) || userEmail.getText().toString().trim().equals(""))
		{
			isRight = false;
			ShowToast(this,"Email 您填写有误，请重新填写");
			return isRight;
		}
		if(userPassword.getText().toString().trim().equals(""))
		{
			isRight = false;
			ShowToast(this,"请输入您的密码");
			return isRight;
		}
		if(!userPassword.getText().toString().equals(userConfirmPassword.getText().toString()))
		{
			isRight = false;
			ShowToast(this,"两次填写的密码必须一致");
			return isRight;
		}
		if(!isNumeric(userHeight.getText().toString()) || userHeight.getText().toString().trim().equals(""))
		{
			isRight = false;
//			TextView heightError = (TextView)findViewById(R.id.registHeight);
			ShowToast(this, "您填写的身高有误，请重新填写");
			return isRight;
		}
		else if(Integer.parseInt(userHeight.getText().toString()) > 250)
		{
			isRight = false;
//			TextView heightError = (TextView)findViewById(R.id.registHeight);
			ShowToast(this, "您填写的身高有误，请重新填写");
			return isRight;
		}
		if(!isNumeric(userWeight.getText().toString())||userWeight.getText().toString().trim().equals(""))
		{
			isRight = false;
//			TextView weightError = (TextView)findViewById(R.id.registWeight);
			ShowToast(this, "您填写的体重有误，请重新填写");
			return isRight;
		}
		else if(Integer.parseInt(userWeight.getText().toString()) > 300)
		{
			isRight = false;
//			TextView weightError = (TextView)findViewById(R.id.registWeight);
			ShowToast(this, "您填写的体重有误，请重新填写");
			return isRight;
		}
		
		return isRight;
	}
    //check email
	public boolean isEmail(String email) {
		String str = "^([a-z0-9a-z]+[-|\\.]?)+[a-z0-9a-z]@([a-z0-9a-z]+(-[a-z0-9a-z]+)?\\.)+[a-za-z]{2,}$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
        
		return m.matches();
	}
	//check input is number or not
	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}
	public void ShowToast(Context context, String strShowMessage) {
		Toast toast = Toast.makeText(context,
				strShowMessage, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	class MonthSpinnerSelectedListener implements OnItemSelectedListener
	{
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
		{
			if(month[position].contains("1") || month[position].contains("3") ||month[position].contains("5") || month[position].contains("7") || month[position].contains("8") || month[position].contains("10") || month[position].contains("12"))
			{
				days = new  String[] {"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
	    				,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
	    				,"27日","28日","29日","30日","31日"};
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(UserRegisterActivity.this,R.layout.spinner_style,days);
				newAdpBirthdayDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
				spinnerDay.setAdapter(newAdpBirthdayDay); 
			}
			else if(month[position].contains("2"))
			{
				if(bLeapYear)
				{
					days = new String[] {"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
	    				,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
	    				,"27日","28日","29日"};
				}
				else
				{
					days = new String[] {"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
		    				,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
		    				,"27日","28日"};
				}
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(UserRegisterActivity.this,R.layout.spinner_style,days);
				newAdpBirthdayDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
				spinnerDay.setAdapter(newAdpBirthdayDay);
			}
			else
			{
				days = new String[]{"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
	    				,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
	    				,"27日","28日","29日","30日"};
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(UserRegisterActivity.this,R.layout.spinner_style,days);
				newAdpBirthdayDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
				spinnerDay.setAdapter(newAdpBirthdayDay); 
			}
		}
		public void onNothingSelected(AdapterView<?> arg0) 
		{
			
		}
	}
	class DaySpinnerSelectedListener implements OnItemSelectedListener
	{
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
		{
		}
		public void onNothingSelected(AdapterView<?> arg0) 
		{
			
		}
	}
	class YearSpinnerSelectedListener implements OnItemSelectedListener
	{
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
		{
			int intSelectedYear = Integer.parseInt(spinnerYear.getSelectedItem().toString());
			 if(intSelectedYear%400==0||(intSelectedYear%100!=0)&&(intSelectedYear%4==0))
			 {
				 bLeapYear = true;
			 }
			 else
			 {
				 bLeapYear = false;
			 }
			 if(bLeapYear && spinnerMonth.getSelectedItem().toString().contains("2"))
			 {
				 days = new String[] {"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
		    				,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
		    				,"27日","28日","29日"};
				 ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(UserRegisterActivity.this,R.layout.spinner_style,days);
					newAdpBirthdayDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
					spinnerDay.setAdapter(newAdpBirthdayDay);
			 }
			 else if(!bLeapYear && spinnerMonth.getSelectedItem().toString().contains("2"))
			 {
				 days = new String[] {"1日","2日","3日","4日","5日","6日","7日","8日","9日","10日","11日","12日"
		    				,"13日","14日","15日","16日","17日","18日","19日","20日","21日","22日","23日","24日","25日","26日"
		    				,"27日","28日"};
				 ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(UserRegisterActivity.this,R.layout.spinner_style,days);
					newAdpBirthdayDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
					spinnerDay.setAdapter(newAdpBirthdayDay);
			 }
		}
		public void onNothingSelected(AdapterView<?> arg0) 
		{
			
		}
	}
	public void RegisterThreadHandle( final String strUserEmail, final String strUserPassword,final String strBirthday, final double strUserHeight, final double strUserWeight, final String strUserSex)
	{
		new Thread()
		{
			@Override
			public void run()
			{
				Control callDatabase = new Control();
				Message msg = new Message();
				msg.what = REGISTER_CHECK_ID;
				Hashtable<String,Object> registState = new Hashtable<String,Object>();
				registState = callDatabase.registerAndLogin(UserRegisterActivity.this, strUserEmail, strUserPassword, strBirthday, strUserHeight, strUserWeight, strUserSex, "", "", "", "");
				if(registState.get("userID").toString().equals("-1"))
				{
		    		msg.arg1 = 0;
				}
				else
				{
					msg.arg1 = 1;
					String sSession = registState.get("sessionID").toString();
					String sUserId = registState.get("userID").toString();
		    		SharedPreferences sharedPreferences = UserRegisterActivity.this.getSharedPreferences("YDL",Context.MODE_PRIVATE);
		    		Editor editor = sharedPreferences.edit();
		    		editor.putString("sUserID",sUserId);
		    		editor.putBoolean("bCurrentRegisterSts",true);
		    		editor.putString("sSession", sSession);
					editor.putString("sUserName", strUserEmail);
					editor.putString("sUserPassword", strUserPassword);
		    		editor.commit();
				}
				handle.sendMessage(msg);
			}
		}.start();
	}
}
